package com.daafan.minilib.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.tsz.afinal.FinalDb;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.daafan.minilib.R;
import com.daafan.minilib.data.BookData;
import com.daafan.minilib.data.BookList;
import com.daafan.minilib.service.BookListService;
import com.daafan.minilib.util.MathUtil;
import com.nostra13.universalimageloader.core.DisplayImageOptions;

public class BookListActivity extends BaseActivity {

	public static final String		BOOK_ID					= "BOOKE_ID";

	ListView						listView_books;
	BooksAdapter					mAdapter;
	List<BookData>					bookList				= new ArrayList<BookData>();
	int[]							progress				= new int[10];						// progress 已下载文件大小 / 需要下载的文件大小

	private String					download_bookId			= "";
	private BookListService			service;

	// 这里需要用到ServiceConnection在Context.bindService和context.unBindService()里用到
	private ServiceConnection		mServiceConnection		= new ServiceConnection() {
																public void onServiceConnected(ComponentName name, IBinder binder) {
																	service = ((BookListService.BookBinder) binder).getService();
																	service.setBookList(bookList);
																}

																public void onServiceDisconnected(ComponentName name) {}
															};

	private Handler					handler					= new Handler();
	private Runnable				beginDownloadRunnable	= new Runnable() {

																@Override
																public void run() {

																	if (service != null) {
																		if (download_bookId != null && !download_bookId.equals("")) {
																			for (BookData tbook : bookList) {
																				if (tbook.bookid.equals(download_bookId)) {

																					service.setBookList(bookList);

																					service.download(tbook.getBookid());
																				}
																			}
																		}
																	} else
																		handler.postDelayed(this, 1000);// service未绑定
																}
															};
	private Runnable				notifyRunnable			= new Runnable() {

																@Override
																public void run() {
																	if (mAdapter != null && update) {
																		update = false;

																		mAdapter.notifyDataSetChanged();
																	}

																	handler.postDelayed(this, 2 * 1000);
																}
															};
	/** 是否需要刷新UI */
	private boolean					update;

	/** 根据id索引TextView */
	private Map<String, TextView>	bookId_progresMap		= new HashMap<String, TextView>();
	private ProgressReciever		reciever				= new ProgressReciever();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_book_list);

		initTopBar("电子书", R.drawable.back, 0);

		listView_books = (ListView) findViewById(R.id.listView_book_list);
		listView_books.setDividerHeight(0);

		mAdapter = new BooksAdapter();
		listView_books.setAdapter(mAdapter);

		// 绑定Service
		Intent intent = new Intent();
		intent.setClass(this, BookListService.class);
		bindService(intent, mServiceConnection, BIND_AUTO_CREATE);

		// 需要下载的图书
		download_bookId = getIntent().getStringExtra(BOOK_ID);

		restoreBookList();
		// reqBookList(1);
		download();

		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(ProgressReciever.ACTION_PROGRESS); // 为BroadcastReceiver指定action，使之用于接收同action的广播
		intentFilter.addAction(ProgressReciever.ACTION_SUCCESS);
		registerReceiver(reciever, intentFilter);

		// 每隔一段时间，ListView刷新一下,显示下载进度
		handler.postDelayed(notifyRunnable, 2 * 1000);
	}

	@Override
	protected void onDestroy() {
		unbindService(mServiceConnection);
		unregisterReceiver(reciever);
		super.onDestroy();
	}

	private void restoreBookList() {
		BookList bookList = new BookList();
		bookList.restore(mContext);
		this.bookList = bookList.datas;

		if (this.bookList.size() == 0)
			Toast.makeText(mContext, "请使用二维码扫描或摇一摇，收藏电子书", Toast.LENGTH_LONG).show();

		mAdapter.notifyDataSetChanged();
	}

	/** 向service请求，下载id={@linkplain #download_bookId}的图书 */
	private void download() {
		// 如果有需要下载图书
		if (download_bookId != null && !download_bookId.equals(""))
			for (BookData tbook : this.bookList) {
				if (tbook.bookid.equals(download_bookId)) {
					handler.post(beginDownloadRunnable);
				}
			}
	}

	@Override
	protected void onTopLeftClick() {
		back();
	}

	@SuppressWarnings("unused")
	private class BooksAdapter extends BaseAdapter {

		ViewHolder	holder;

		class ViewHolder {
			ImageView	img_book;

			TextView	tv_book_title;
			TextView	tv_book_author;
			// TextView tv_book_ISBN;

			TextView	tv_progress;
			ProgressBar	progressBar;		// 每1~2秒刷新一次
			Button		btn_downOrPause;
		}

		private void setVisible(ViewHolder holder, int visible) {
			if (holder == null)
				return;

			holder.img_book.setVisibility(visible);

			holder.tv_book_title.setVisibility(visible);
			holder.tv_book_author.setVisibility(visible);
			// holder.tv_book_ISBN.setVisibility(visible);

			holder.tv_progress.setVisibility(visible);
			holder.progressBar.setVisibility(visible);
			holder.btn_downOrPause.setVisibility(visible);
		}

		@Override
		public int getCount() {
			int size = 5;
			if (bookList != null)
				size = (size = bookList.size()) < 5 ? 5 : size;

			return size;
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				convertView = getLayoutInflater().inflate(R.layout.item_book_list, null);

				holder = new ViewHolder();

				holder.img_book = (ImageView) convertView.findViewById(R.id.img_book);

				holder.tv_book_title = (TextView) convertView.findViewById(R.id.tv_book_item_title);
				holder.tv_book_author = (TextView) convertView.findViewById(R.id.tv_book_item_author);
				// holder.tv_book_ISBN = (TextView) convertView.findViewById(R.id.tv_book_item_ISBN);

				holder.tv_progress = (TextView) convertView.findViewById(R.id.tv_book_item_progress);
				holder.progressBar = (ProgressBar) convertView.findViewById(R.id.progressBar_book_item);
				holder.btn_downOrPause = (Button) convertView.findViewById(R.id.btn_book_item_down);

				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			BookData book = new BookData();
			if (position < bookList.size()) {
				book = bookList.get(position);
				setVisible(holder, View.VISIBLE);

				bookId_progresMap.put(book.bookid, holder.tv_progress);
			} else {
				setVisible(holder, View.INVISIBLE);
			}

			DisplayImageOptions options = new DisplayImageOptions.Builder().cloneFrom(getApp().getDisplayOptions())
					.showImageOnFail(R.drawable.book_bg).showImageForEmptyUri(R.drawable.book_bg).showStubImage(R.drawable.book_bg)
					.build();

			// 显示图书图片
			if (book.imgurl != null && !book.imgurl.equals("")) {
				mImageLoader.displayImage(book.imgurl, holder.img_book, options);
				holder.img_book.setVisibility(View.VISIBLE);
			}

			// 图书title
			holder.tv_book_title.setText(book.bookname);

			// 作者
			holder.tv_book_author.setText(book.author);// + " 著"

			// ISBN
			// holder.tv_book_ISBN.setText("ISBN:" + book.bookid);

			// 显示下载进度
			double progress;
			if (book.countBit > 1)
				progress = (double) book.current * 100 / book.countBit;
			else
				progress = 0;
			holder.tv_progress.setText(MathUtil.remain(progress, 2) + "%");

			// 进度条进度
			holder.progressBar.setMax(100);
			holder.progressBar.setProgress((int) progress);

			final BookData cacheBook = book;

			if (service != null && service.isDownloading(book.bookid)) {
				holder.btn_downOrPause.setBackgroundDrawable(getResources().getDrawable(R.drawable.pause));

			} else if (book.isFinish) {
				holder.btn_downOrPause.setVisibility(View.GONE);
			} else
				holder.btn_downOrPause.setBackgroundDrawable(getResources().getDrawable(R.drawable.down));

			// 下载按钮
			if (progress == 100)
				holder.btn_downOrPause.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						Toast.makeText(mContext, "已下载完毕", 0).show();
					}
				});
			else
				holder.btn_downOrPause.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						String bookId = cacheBook.getBookid();

						String target = BookListService.getAPKName(bookId);

						if (service != null && !service.isDownloading(bookId)) {
							service.setBookList(bookList);
							service.download(bookId);

							holder.btn_downOrPause.setBackgroundDrawable(getResources().getDrawable(R.drawable.pause));
						} else {
							// 调用stop()方法停止下载
							service.stopDownload(bookId);
							holder.btn_downOrPause.setBackgroundDrawable(getResources().getDrawable(R.drawable.down));

							Toast.makeText(mContext, "暂停下载", 0).show();
						}
					}
				});

			// 长按删除Book
			if (position < bookList.size()) {
				final String bookId = book.bookid;
				System.out.println("setOnLongClickListener position=" + position);
				convertView.setOnLongClickListener(new OnLongClickListener() {

					@Override
					public boolean onLongClick(View v) {
						System.out.println("LongClick  position=" + position);

						showConfirmDialog("提示", "是否删除", new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog, int which) {
								FinalDb db = FinalDb.create(mContext);

								db.deleteByWhere(BookData.class, "bookid=\"" + bookId + "\"");

								handler.post(new Runnable() {

									@Override
									public void run() {
										// 让本书消失
										for (int i = 0; i < bookList.size(); i++) {
											BookData book = bookList.get(i);
											if (book.bookid == bookId) {
												bookList.remove(i);
											}
										}

										mAdapter.notifyDataSetChanged();
									}
								});
							}
						});

						return false;
					}
				});
			} else
				convertView.setOnLongClickListener(new OnLongClickListener() {

					@Override
					public boolean onLongClick(View v) {
						return false;
					}
				});

			if (book.isFinish) {
				final String pdfPath = book.pdfPath;
				convertView.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// Toast.makeText(mContext, "打开pdf", 0).show();

						// 打开pdf
						File file = new File(pdfPath);

						if (file.exists()) {
							Uri path = Uri.fromFile(file);
							Intent intent = new Intent(Intent.ACTION_VIEW);
							intent.setDataAndType(path, "application/pdf");
							intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

							try {
								startActivity(intent);
							} catch (ActivityNotFoundException e) {
								Toast.makeText(mContext, "No Application Available to View PDF", Toast.LENGTH_SHORT).show();
							}
						}
					}
				});
			} else {
				if (position < bookList.size())
					convertView.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {
							Toast.makeText(mContext, "下载未完成", 0).show();
						}
					});
			}

			return convertView;
		}
	}

	public class ProgressReciever extends BroadcastReceiver {
		public static final String	BOOKID			= "BOOKID";
		public static final String	PROGRESS		= "PROGRESS";
		public static final String	ACTION_PROGRESS	= "PROGRESS";
		public static final String	ACTION_SUCCESS	= "SUCCESS";

		@Override
		public void onReceive(Context context, Intent intent) {
			String bookId = intent.getStringExtra(BOOKID);

			if (intent.getAction().equals(ACTION_PROGRESS)) {
				// System.out.println("onReceive ACTION_PROGRESS");

				// 要更新的Book是否正在显示
				if (bookId_progresMap.containsKey(bookId)) {
					double progress = intent.getDoubleExtra(PROGRESS, 0);
					System.out.println("progress=" + progress);

					update = true;

					// TextView tv_progress = bookId_progresMap.get(bookId);
					// tv_progress.setText(MathUtil.remain(progress, 2) + "%");
					// mAdapter.notifyDataSetChanged();
				}
			} else if (intent.getAction().equals(ACTION_SUCCESS)) {
				mAdapter.notifyDataSetChanged();
			}
		}
	}
}
